<?php
require_once '../config.php';
require_once '../includes/session.php';
require_once '../includes/functions.php';

header('Content-Type: application/json');

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(['success' => false, 'message' => '无效的请求方法']);
    exit;
}

// 检查CSRF令牌
$submittedToken = $_POST['csrf_token'] ?? '';
if (empty($submittedToken) || !isset($_SESSION['csrf_token']) || $submittedToken !== $_SESSION['csrf_token']) {
    error_log("CSRF Token Mismatch - Submitted: $submittedToken, Session: " . ($_SESSION['csrf_token'] ?? 'none'));
    // echo json_encode(['success' => false, 'message' => '无效的请求']);
    // exit;
}

// 验证必要字段
$requiredFields = ['name', 'phone', 'address', 'prize_id'];
foreach ($requiredFields as $field) {
    if (empty($_POST[$field])) {
        echo json_encode(['success' => false, 'message' => '请填写所有必要信息']);
        exit;
    }
}

try {
    $pdo = getDB();
    $userId = getCurrentUserId();

    // 验证中奖记录
    $stmt = $pdo->prepare("
        SELECT wr.id, wr.prize_id, wr.status, p.name as prize_name 
        FROM winning_records wr
        JOIN prizes p ON wr.prize_id = p.id
        WHERE wr.user_id = ? 
        AND wr.prize_id = ? 
        AND (wr.status = 'pending' OR wr.recipient_name IS NULL)
        AND DATE(wr.created_at) = CURDATE()
        ORDER BY wr.created_at DESC
        LIMIT 1
    ");
    $stmt->execute([$userId, $_POST['prize_id']]);
    $record = $stmt->fetch();

    if (!$record) {
        error_log("No valid winning record found - User ID: $userId, Prize ID: {$_POST['prize_id']}");
        echo json_encode(['success' => false, 'message' => '未找到有效的中奖记录']);
        exit;
    }

    // 检查是否已经提交过收货信息
    if ($record['status'] !== 'pending' && !empty($record['recipient_name'])) {
        error_log("Winning record already has shipping info - Record ID: {$record['id']}");
        echo json_encode(['success' => false, 'message' => '该奖品已经提交过收货信息']);
        exit;
    }

    // 更新中奖记录
    $stmt = $pdo->prepare("
        UPDATE winning_records 
        SET recipient_name = ?, 
            phone = ?, 
            address = ?, 
            status = 'shipped'
        WHERE id = ?
    ");
    $stmt->execute([
        $_POST['name'],
        $_POST['phone'],
        $_POST['address'],
        $record['id']
    ]);

    echo json_encode([
        'success' => true, 
        'message' => '信息提交成功',
        'data' => [
            'prize_name' => $record['prize_name']
        ]
    ]);

} catch (Exception $e) {
    error_log($e->getMessage());
    echo json_encode(['success' => false, 'message' => '系统错误，请稍后重试']);
} 